package com.webex.ta.hydra.gui.macro.action;

import com.webex.ta.hydra.Constants;
import com.webex.ta.hydra.core.macro.MacroDefinition;
import com.webex.ta.hydra.core.macro.MacroSerializer;
import com.webex.ta.hydra.gui.action.ActionHandler;
import com.webex.ta.hydra.gui.action.ActionNames;
import com.webex.ta.hydra.gui.macro.MacroEditorContext;
import com.webex.ta.hydra.gui.util.FileDialoger;
import com.webex.ta.hydra.util.HydraUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-14
 * Time: 15:55:26
 */
public class MacroOpenAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.MACR0_OPEN);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        JFileChooser chooser = FileDialoger.promptToOpenFile(new String[]{Constants.HYDRA_MACRO_EXTENSION});
        if (chooser == null) {
            return;
        }
        File selectedFile = chooser.getSelectedFile();
        if (selectedFile != null) {
            // We must ask the user if it is ok to close current project
            if (!MacroCloseAction.performAction(e))
                return;

            loadProjectFile(e, selectedFile);
        }
    }

    static void loadProjectFile(ActionEvent e, File f) {
        InputStream istream = null;
        try {
            istream = new FileInputStream(f);
            Vector<MacroDefinition> defs = MacroSerializer.loadMacroDefinitions(istream);
            MacroEditorContext ctx = MacroEditorContext.getInstance();
            ctx.getEditor().getListModel().setDefinitions(defs);
            ctx.setMacroDefFile(f.getAbsolutePath());
            istream.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            HydraUtils.closeQuietly(istream);
        }
    }
}
